package edu.scau.pos215.service.impl;

import cn.hutool.core.util.IdUtil;
import edu.scau.pos215.constants.SaleItemStatusConstants;
import edu.scau.pos215.constants.SaleStatusConstants;
import edu.scau.pos215.domain.Payment;
import edu.scau.pos215.domain.ProductDescription;
import edu.scau.pos215.domain.Sale;
import edu.scau.pos215.domain.SaleItem;
import edu.scau.pos215.mapper.SaleItemMapper;
import edu.scau.pos215.mapper.SaleMapper;
import edu.scau.pos215.service.ISaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SaleServiceImpl implements ISaleService {

    private Sale currentSale;
    @Autowired
    private SaleItemMapper saleItemMapper;
    @Autowired
    private SaleMapper saleMapper;

    /**
     * 开始新的销售
     * @return currentSale对象
     */
    @Override
    public Sale makeNewSale() {
        currentSale = new Sale();
        Date saleDate = new Date();
        currentSale.setSaleTime(saleDate);
        String saleNo = "so-"+ IdUtil.getSnowflakeNextId();
        currentSale.setSaleNo(saleNo);
        currentSale.setStatus(SaleStatusConstants.ORDER_RESERVED);
        currentSale.setTotal(new BigDecimal("0.00"));
        return currentSale;
    }
    /**
     * 实例化SaleItem
     * @param product 商品对象
     * @param quantity 数量
     */

    @Override
    public void makeLineItem(ProductDescription product, int quantity) {
        // 判断商品是否已录入
        if(!isEntered(product.getProductSn(),quantity)){
            SaleItem saleItem = new SaleItem();
            saleItem.setProductId(product.getProductId());
            saleItem.setProductDescription(product);
            saleItem.setPrice(product.getPrice());
            saleItem.setQuantity(quantity);
            currentSale.getSaleItems().add(saleItem);
        }
    }

    /**
     * 结束订单商品录入
     * @return 总金额
     */

    @Override
    public BigDecimal endSale() {
        BigDecimal total = this.getTotal();
        currentSale.setTotal(total);
        currentSale.setStatus(SaleStatusConstants.ORDER_RESERVED);
        currentSale.setCreateTime(new Date());
        saleMapper.insertSale(currentSale);
        //将订单中商品持久化
        this.insertSaleItemsOfCurrentSale(currentSale);
        return total;
    }

    /**
     * 订单支付
     * @param cashTendered 付款金额
     * @return 找零
     */
    @Override
    public BigDecimal makePayment(BigDecimal cashTendered) {
        BigDecimal total = currentSale.getTotal();
        Payment payment = new Payment();
        payment.setAmount(total);
        payment.setPayTime(new Date());
        currentSale.setPayment(payment);
        currentSale.setStatus(SaleStatusConstants.ORDER_PAID);
        currentSale.setUpdateTime(new Date());
        // change为找零
        BigDecimal change = cashTendered.subtract(total);
        saleMapper.updateSale(currentSale);
        //更新订单商品明细的状态和更新时间
        this.updateSaleItemsOfCurrentSaleForMakePayment(currentSale);
        return change;
    }

    /**
     * 判断商品是否已录入
     * @param itemSn
     * @param quantity
     * @return
     */
    private boolean isEntered(String itemSn,int quantity){
        boolean flag = false;
        for(SaleItem si : currentSale.getSaleItems()){
            // 如果已经录入则修改数量
            if(itemSn.equals(si.getProductDescription().getProductSn())) {
                flag = true;
                int quantityOriginal = si.getQuantity();
                si.setQuantity(quantityOriginal + quantity);
            }
        }
        return flag;
    }

    /**
     * 计算总金额
     * @return
     */
    private BigDecimal getTotal(){
        BigDecimal total = new BigDecimal(0);
        List<SaleItem> saleItemList = currentSale.getSaleItems();
        for(SaleItem si : saleItemList) {
            total = total.add(si.getSubTotal());
        }
        return total;
    }

    /**
     * 将Sale中的saleItem存入数据库
     * @param currentSale 当前sale对象
     */
    private void insertSaleItemsOfCurrentSale(Sale currentSale) {
        List<SaleItem> saleItemList = currentSale.getSaleItems();
        List<SaleItem> list = new ArrayList<>();
        for(SaleItem si : saleItemList) {
            si.setStatus(SaleItemStatusConstants.ITEM_RESERVED);
            si.setDelFlag("0");
            si.setCreateTime(new Date());
            si.setSaleId(currentSale.getSaleId());
            list.add(si);
        }
        saleMapper.batchInsertSaleItemOfCurrentSale(list);
    }

    /**
     * 支付后修改商品明细
     * 修改【状态】和【更新时间】
     * @param currentSale 当前sale对象
     */
    private void updateSaleItemsOfCurrentSaleForMakePayment(Sale currentSale) {
        SaleItem param = new SaleItem();
        param.setSaleId(currentSale.getSaleId());
        List<SaleItem> saleItems = saleItemMapper.selectSaleItemList(param);
        for (SaleItem si : saleItems) {
            si.setStatus(SaleItemStatusConstants.ITEM_PAID);
            si.setUpdateTime(new Date());
            saleItemMapper.updateSaleItem(si);
        }
    }
    /**
     * 冗余，与下方的changeNum相同
     * 修改订单商品数量
     */
    public void changeSaleItemNum(String itemSn, int quantity){
        List<SaleItem> saleItems = currentSale.getSaleItems();
        for(SaleItem si : saleItems) {
            if (itemSn.equals(si.getProductDescription().getProductSn())){
                si.setQuantity(quantity);
            }
        }
    }

    /**
     * 删除商品
     */
    @Override
    public void deleteSaleItem(String itemSn) {
        List<SaleItem> saleItems = currentSale.getSaleItems();
        for (int i = 0; i < saleItems.size(); i++) {
            if (itemSn.equals(saleItems.get(i).getProductDescription().getProductSn())) {
                saleItems.remove(i);
                break;
            }
        }
    }


    /**
     * 修改商品数量
     */
    @Override
    public void changeNum(String itemSn, int quantity) {
        List<SaleItem> saleItems = currentSale.getSaleItems();
        for(SaleItem si : saleItems){
            if (itemSn.equals(si.getProductDescription().getProductSn())){
                si.setQuantity(quantity);
            }
        }
    }
}
